<template>
  <div class="products-dashboard">
    <!-- 关键指标卡片 -->
    <el-row :gutter="20" class="metrics-row">
      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="商品总数" :value="metrics.totalProducts">
            <template #suffix>个</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.productsTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.productsTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.productsTrend) }}%
            </span>
            <span class="trend-label">较上月</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="在售商品" :value="metrics.onSaleProducts">
            <template #suffix>个</template>
          </el-statistic>
          <div class="metric-trend">
            <span class="trend-label">占比 {{ (metrics.onSaleProducts / metrics.totalProducts * 100).toFixed(1) }}%</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="平均售价" :value="metrics.avgPrice" :precision="2">
            <template #prefix>¥</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.priceTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.priceTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.priceTrend) }}%
            </span>
            <span class="trend-label">较上月</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="metric-card">
          <el-statistic title="SKU总数" :value="metrics.totalSKUs">
            <template #suffix>个</template>
          </el-statistic>
          <div class="metric-trend">
            <span :class="['trend', metrics.skuTrend > 0 ? 'up' : 'down']">
              <el-icon><CaretTop v-if="metrics.skuTrend > 0" /><CaretBottom v-else /></el-icon>
              {{ Math.abs(metrics.skuTrend) }}%
            </span>
            <span class="trend-label">较上月</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>商品数量趋势</span>
              <el-radio-group v-model="trendType" size="small" @change="loadTrendChart">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="year">近12月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <donut title="商品分类" model="product_catalog_summary" dataKey="num" labelKey="name"></donut>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card>
          <Bar
            title="TOP10 热销商品"
            :data="hotProductsData"
            xAxisKey="name"
            yAxisKey="value"
            :seriesNames="['销量']"
            horizontal
            :colors="['#667eea']"
            :borderRadius="4"
          />
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <pie title="品牌分布" model="product_brand_num_list" dataKey="num" labelKey="name"></pie>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card>
          <Bar
            title="价格区间分布"
           model="product_with_range_list"
            xAxisKey="name"
            yAxisKey="value"
            :seriesNames="['商品数量']"
            yAxisName="商品数量"
            xAxisName="价格区间(元)"
            :colors="['#4facfe']"
            :borderRadius="4"
          />
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <donut title="商品状态统计" model="product_state_summary" dataKey="num" labelKey="name"></donut>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品统计表格 -->
    <el-card class="mt-20">
      <template #header>
        <div class="card-header">
          <span>商品分类统计</span>
          <el-button type="primary" size="small" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </template>
      <el-table :data="categoryStats" stripe border>
        <el-table-column prop="categoryName" label="分类名称" width="200" />
        <el-table-column prop="productCount" label="商品数量" width="120" align="right" />
        <el-table-column prop="onSaleCount" label="在售数量" width="120" align="right" />
        <el-table-column prop="avgPrice" label="平均价格" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.avgPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalSales" label="总销量" width="120" align="right" />
        <el-table-column prop="totalAmount" label="总销售额" width="150" align="right">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="growth" label="增长率" width="120" align="right">
          <template #default="{ row }">
            <span :class="['growth-value', row.growth > 0 ? 'positive' : 'negative']">
              {{ row.growth > 0 ? '+' : '' }}{{ row.growth }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleViewCategory(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { CaretTop, CaretBottom, Download } from '@element-plus/icons-vue'
import Donut from "@/components/echarts/Donut.vue";
import Pie from "@/components/echarts/Pie.vue";
import Bar from "@/components/echarts/Bar.vue";

// 响应式数据
const trendType = ref('week')
const trendChartRef = ref(null)

let trendChart = null

// 热销商品数据
const hotProductsData = ref([
  { name: '商品A', value: 3150 },
  { name: '商品B', value: 2920 },
  { name: '商品C', value: 2680 },
  { name: '商品D', value: 2450 },
  { name: '商品E', value: 2280 },
  { name: '商品F', value: 2050 },
  { name: '商品G', value: 1850 },
  { name: '商品H', value: 1680 },
  { name: '商品I', value: 1450 },
  { name: '商品J', value: 1250 }
])

// 价格区间数据
const priceRangeData = ref([
  { name: '0-50', value: 285 },
  { name: '50-100', value: 425 },
  { name: '100-200', value: 538 },
  { name: '200-500', value: 468 },
  { name: '500-1000', value: 286 },
  { name: '1000+', value: 154 }
])

// 指标数据
const metrics = reactive({
  totalProducts: 1856,
  productsTrend: 8.5,
  onSaleProducts: 1542,
  avgPrice: 458.65,
  priceTrend: -2.3,
  totalSKUs: 3254,
  skuTrend: 12.3
})

// 分类统计数据
const categoryStats = ref([
  {
    categoryName: '电子产品',
    productCount: 458,
    onSaleCount: 425,
    avgPrice: 2850.00,
    totalSales: 15680,
    totalAmount: 44688000.00,
    growth: 15.8
  },
  {
    categoryName: '服装鞋帽',
    productCount: 326,
    onSaleCount: 298,
    avgPrice: 285.50,
    totalSales: 28950,
    totalAmount: 8265225.00,
    growth: 8.3
  },
  {
    categoryName: '食品饮料',
    productCount: 285,
    onSaleCount: 268,
    avgPrice: 45.80,
    totalSales: 98500,
    totalAmount: 4511300.00,
    growth: -3.5
  },
  {
    categoryName: '家居用品',
    productCount: 198,
    onSaleCount: 175,
    avgPrice: 156.20,
    totalSales: 12350,
    totalAmount: 1929070.00,
    growth: 12.5
  },
  {
    categoryName: '美妆护肤',
    productCount: 156,
    onSaleCount: 148,
    avgPrice: 385.00,
    totalSales: 8950,
    totalAmount: 3445750.00,
    growth: 22.6
  }
])

// 加载趋势图表
const loadTrendChart = () => {
  if (!trendChartRef.value) return

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const dataMap = {
    week: {
      dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      products: [1800, 1820, 1835, 1842, 1850, 1855, 1856],
      onSale: [1520, 1528, 1535, 1538, 1540, 1542, 1542]
    },
    month: {
      dates: Array.from({ length: 30 }, (_, i) => `${i + 1}日`),
      products: Array.from({ length: 30 }, (_, i) => 1720 + i * 4.5),
      onSale: Array.from({ length: 30 }, (_, i) => 1450 + i * 3)
    },
    year: {
      dates: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      products: [1520, 1555, 1590, 1625, 1660, 1695, 1730, 1765, 1800, 1820, 1840, 1856],
      onSale: [1280, 1310, 1340, 1370, 1400, 1430, 1460, 1485, 1510, 1525, 1535, 1542]
    }
  }

  const data = dataMap[trendType.value]

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['商品总数', '在售商品']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '商品总数',
        type: 'line',
        smooth: true,
        data: data.products,
        itemStyle: { color: '#409EFF' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        }
      },
      {
        name: '在售商品',
        type: 'line',
        smooth: true,
        data: data.onSale,
        itemStyle: { color: '#67C23A' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103, 194, 58, 0.5)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ])
        }
      }
    ]
  }

  trendChart.setOption(option)
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  trendChart?.resize()
}

// 方法
const handleExport = () => {
  ElMessage.success('正在导出数据...')
}

const handleViewCategory = (row) => {
  ElMessage.info(`查看分类：${row.categoryName}`)
}

// 生命周期
onMounted(() => {
  setTimeout(() => {
    loadTrendChart()
    window.addEventListener('resize', handleResize)
  }, 100)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
})
</script>

<style scoped>
.products-dashboard {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.metrics-row {
  margin-bottom: 20px;
}

.metric-card {
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.metric-trend {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  font-weight: 600;
}

.trend.up {
  color: #67c23a;
}

.trend.down {
  color: #f56c6c;
}

.trend-label {
  font-size: 12px;
  color: #909399;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.growth-value {
  font-weight: bold;
}

.growth-value.positive {
  color: #67c23a;
}

.growth-value.negative {
  color: #f56c6c;
}
</style>

